<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class TrainingLevels extends CI_Model {

	function __construct() {
        parent::__construct();
    }

    public function exists($trainingLevel) {
    	$id = self::getId($trainingLevel);
    	return ($id > 0);
    }

	public function getAll() {
		$sql = "SELECT " .
			   "tl.TrainingLevelId AS Id, " .
			   "tl.TrainingLevel, " .
			   "tl.Description " .
			   "FROM " .
			   "traininglevels AS tl " .
			   "ORDER BY " .
			  "tl.TrainingLevel";

		$query = $this->db->query($sql);
		return $query->result_array();
	}

	public function getId($trainingLevel) {
		$id = 0;

		$sql = "SELECT " .
			   "tl.TrainingLevelId AS Id " .
			   "FROM " .
			   "traininglevels AS tl " .
			   "WHERE " .
			   "(tl.TrainingLevel LIKE " . $this->db->escape((string) $trainingLevel) . ")";

		$query = $this->db->query($sql);
		if ($query->num_rows() > 0) {
			$row = $query->row_array();
			$id = $row['Id'];
		}

		return $id;
	}

	public function save($updates) {
		$saved = true;

		$this->db->trans_begin();

		foreach ($updates as $update) {
			$sql = '';
			$params = array();

			if ($update->RowState == 'added') {
				$sql = "INSERT INTO `traininglevels` " .
					   "(`TrainingLevel`, `Description`, `DateCreated`) " .
					   "VALUES " .
					   "(?, ?, NOW())";

				$params = array( $update->TrainingLevel, $update->Description );
			}
			else if ($update->RowState == 'modified') {
				$sql = "UPDATE `traininglevels` SET " .
					   "`TrainingLevel` = ?, `Description` = ? " .
					   "WHERE " .
					   "(`TrainingLevelId` = ?)";

				$params = array( $update->TrainingLevel, $update->Description, $update->Id );		   
			}
			else if ($update->RowState == 'deleted') {
				$sql = "DELETE FROM `traininglevels` WHERE (`TrainingLevelId` = ?)";
				$params = array( $update->Id );
			}
			else {

			}

			if (trim($sql) != '') $this->db->query($sql, $params);
		}

		if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $saved = false;
        }
        else {
            $this->db->trans_commit();
        }

		return $saved;
	}

}